package com.hc.tenant.config;

import com.hc.common.log.aspect.LogAspect;
import com.hc.tenant.domain.MqttMsgSend;
import com.hc.tenant.service.IMqttMsgSendService;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;
import java.util.List;

@Configuration
@EnableAsync
public class ScheduleConfig {
    @Autowired
    private MqttPushClient mqttPushClient;

    @Autowired
    private IMqttMsgSendService mqttMsgSendService;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);


    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); //计划任务线程池，每来一个任务创一个线程，直至线程池满
        taskScheduler.setPoolSize(4);
        return taskScheduler;
    }

    @Async
    @Scheduled(cron = "0/30 * * * * ?")
    public void refreshBean() {
        mqttPushClient.refresh();
    }

    @Async
    @Scheduled(cron = "0/30 * * * * ?")
    public void mqttPublish(){

        List<MqttMsgSend> sendList = mqttMsgSendService.selectMqttMsgSendLimitRetryList(3);
        for(MqttMsgSend temp: sendList){
                temp.setLastSendTime(new Date());
            try {
                mqttPushClient.publish(temp.getTopicName(), temp.getMsg());
                temp.setSuccess(1);
                mqttMsgSendService.updateMqttMsgSend(temp);
            } catch (MqttException e) {
                temp.setSuccess(0);
                temp.setRetry(temp.getRetry()+1);
                mqttMsgSendService.updateMqttMsgSend(temp);
                log.error("异常信息:{}", e.getMessage());
                e.printStackTrace();
            }

        }
    }


}
